def bug_connect(bug_task,user_info_by_realname,type):
    user_bug_counts = {}
    for bug_task_ in bug_task:
        # 检查tasks1中的'finishedBy（完成）'字段是否与tasks2中的'realname'字段匹配
        # print(task_1['finishedBy（完成）'])
        # 如果用户不在字典中，则添加该用户
        if bug_task_["resolvedBy"] and bug_task_["resolvedBy"] not in user_bug_counts:
            user_bug_counts[bug_task_["resolvedBy"]] = {'assignedTo':0,'submitted_bug': 0, 'completed_bug': 0, 'uncompleted_bug': 0,'closed_bug': 0}
        if bug_task_["assignedTo"] and bug_task_["assignedTo"]!="closed" and bug_task_["assignedTo"] not in user_bug_counts:
            user_bug_counts[bug_task_["assignedTo"]] = {'assignedTo':0,'submitted_bug': 0, 'completed_bug': 0, 'uncompleted_bug': 0,'closed_bug': 0}
        if bug_task_["openedBy"] and bug_task_["openedBy"] not in user_bug_counts:
            user_bug_counts[bug_task_["openedBy"]] = {'assignedTo':0,'submitted_bug': 0, 'completed_bug': 0, 'uncompleted_bug': 0,'closed_bug': 0}

        if bug_task_["closedBy"] and  bug_task_["closedBy"] not in user_bug_counts:
            user_bug_counts[bug_task_["closedBy"]] = {'assignedTo':0,'submitted_bug': 0, 'completed_bug': 0, 'uncompleted_bug': 0,'closed_bug': 0}
        #指派
        if bug_task_["assignedTo"] and bug_task_["assignedTo"]!="closed" :
            user_bug_counts[bug_task_["assignedTo"]]['assignedTo'] += 1

        #已完成  #已完成： 完成人不空
        if bug_task_["resolvedBy"]:
            user_bug_counts[bug_task_["resolvedBy"]]['completed_bug'] += 1
        if bug_task_["closedBy"]:
            user_bug_counts[bug_task_["closedBy"]]['closed_bug'] += 1
        #未完成
        if bug_task_["assignedTo"] and bug_task_["assignedTo"]!="closed" and not bug_task_["resolvedBy"]:
            user_bug_counts[bug_task_["assignedTo"]]['uncompleted_bug'] += 1
        if bug_task_["openedBy"] and not bug_task_["assignedTo"] and not bug_task_["resolvedBy"]:
            user_bug_counts[bug_task_["openedBy"]]['uncompleted_bug'] += 1
        if bug_task_["openedBy"]:
            # print('1',bug_task_["openedBy"])
            # print('2',user_bug_counts)
            user_bug_counts[bug_task_["openedBy"]]['submitted_bug'] += 1



    bug_new_ = []
    for user_,u_d in user_info_by_realname.items():

        if user_ in user_bug_counts:
            dict1 = u_d.copy()
            dict2 = user_bug_counts[user_]
            dict1.update(dict2)
            #print("dict1:",dict1)
        else:
            dict1 = u_d.copy()
            dict2= {"assignedTo":0,'submitted_bug': 0, 'completed_bug': 0, 'uncompleted_bug': 0,'closed_bug': 0}
            dict1.update(dict2)
            #print("dict1:", dict1)
        if type in u_d["name"]:
            bug_new_.append(dict1)
            #print("dict1",dict1)
    # print("user数据,拿出来的数据",len(user_info_by_realname),len(bug_new_))

    return bug_new_
def calculate_department_scores_with_rank(defect_counts):
    bug_d_=[]
    department_defects = {}
    for dict_u in defect_counts:

        if dict_u["dept"] not in department_defects:
            department_defects[dict_u["dept"]] = []
        department_defects[dict_u["dept"]].append((dict_u["account"], dict_u["submitted_bug"]))

        # Calculate scores and ranks for each department
    for department, users_defects in department_defects.items():
        #print("users_defects",users_defects)
        sorted_defects = sorted(users_defects, key=lambda x: x[1],reverse=True)
        #print("sorted_defects:",sorted_defects)
        tem_rank = list(sorted(set([i for _, i in sorted_defects if i!=0]),reverse=True))  # if i!=0
        for i, (account,submitted_bug) in enumerate(sorted_defects, start=1):
            dict_l = {}
            if submitted_bug == 0:
                rank = len(tem_rank) + 1
            else:
                rank = tem_rank.index(submitted_bug) + 1
                # Determine the score based on the ranking
            if 2 > len(tem_rank) >= 1:
                score = 100
            elif len(tem_rank) == 2:
                if rank == 1:
                    score = 100
                if rank == 2:
                    score = 75
            elif len(tem_rank) == 3:
                if rank == 1:
                    score = 100
                if rank == 2:
                    score = 75
                if rank == 3:
                    score = 50
            else:
                if rank <= len(tem_rank) *  0.25:
                    score = 100
                elif rank <= len(tem_rank) * 0.5:
                    score = 75
                elif rank <= len(tem_rank) *  0.75:
                    score = 50
                else:
                    score = 25

            if submitted_bug == 0:
                score = 0
                rank = len(tem_rank) + 1

            dict_l["name"] = account
            dict_l['rank'] = rank
            dict_l['score'] = score
            bug_d_.append(dict_l)
            # print( department,i, (account,submitted_bug),score,rank)

    for dict_u in defect_counts:
        for dict_l in bug_d_:
            if dict_u["account"] == dict_l['name']:
                dict_u["rank"] = dict_l["rank"]
                dict_u["score"] = dict_l["score"]
    # print(len(defect_counts), len(bug_d_))
    return defect_counts

def submmit_bug(bug_task, user_tasks):
    # import csv
    # step3 提交缺陷数 25%
    # Calculate the scores and ranks
    type = "测试"
    # bug_file = open('bug.csv', 'r')
    # bug_task = csv.DictReader(bug_file)
    # user_file = open('user.csv', 'r')
    # user_tasks = csv.DictReader(user_file)
    user_info_by_realname = {task['account']: task for task in user_tasks}
    bug_new = bug_connect(bug_task, user_info_by_realname, "测试")
    scores_with_rank = calculate_department_scores_with_rank(bug_new)

    return scores_with_rank
    # print(len(scores_with_rank))
    # csv_filename = './提交缺陷数 25%.csv'
    # with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
    #     fieldnames = scores_with_rank[0].keys()
    #     writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    #     writer.writeheader()
    #     for user_data in scores_with_rank:
    #         writer.writerow(user_data)

# Print the user name, department, rank, and score for each user
# for defects in defect_scores:
#     print(
#         f"部门: {defects['部门']}，岗位: {defects['岗位']}, submitted_bug: {defects['submitted_bug']}, Score: {defects['score']}")